package com.aishua.aishuawallet.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.aishua.aishuawallet.Constant;
import com.aishua.aishuawallet.R;
import com.aishua.aishuawallet.bean.ReqTransBean;
import com.aishua.aishuawallet.bean.ReqTransnation;
import com.aishua.aishuawallet.diydialog.LoadingDialog;
import com.aishua.aishuawallet.mina.MianManager;
import com.aishua.aishuawallet.mina.MinaResultLIstener;
import com.aishua.aishuawallet.utils.LogUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.zxing.client.result.ParsedResultType;
import com.mylhyl.zxing.scanner.encode.QREncode;


import org.apache.mina.core.session.IoSession;
import org.spongycastle.jce.ECKeyUtil;
import org.spongycastle.util.encoders.Hex;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.ECKeyPair;
import org.web3j.crypto.Hash;
import org.web3j.crypto.Keys;
import org.web3j.crypto.RawTransaction;
import org.web3j.crypto.TransactionEncoder;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.Web3jFactory;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.response.EthBlock;
import org.web3j.protocol.core.methods.response.EthGasPrice;
import org.web3j.protocol.core.methods.response.EthGetBalance;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import org.web3j.protocol.core.methods.response.EthSendTransaction;
import org.web3j.protocol.core.methods.response.EthTransaction;
import org.web3j.protocol.core.methods.response.Web3ClientVersion;
import org.web3j.protocol.http.HttpService;
import org.web3j.utils.Convert;
import org.web3j.utils.Numeric;

import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/**
 * Created by aishua on 2018/7/31.
 */

public class TestActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "TestActivity";
    private Button btn_generate;
    private Button btn_getcode;
    private ImageView img_code;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

//        initView();
//        initData();
//        testWeb3j();
//        test();
//        LogUtils.v(TAG + "eth:" + Convert.toWei("0.000000005", Convert.Unit.ETHER).stripTrailingZeros().toPlainString());
//
//        LogUtils.v(TAG + "eth:" + Convert.fromWei((25200 * 21000) + "", Convert.Unit.ETHER).stripTrailingZeros().toPlainString());
//
        getETHtras();
//       TransactionTest();
//        initView1();
//        registerBroadcast();

//        getDataAsync();






    }


    private void initView() {

        btn_generate = findViewById(R.id.btn_generate);
        btn_getcode = findViewById(R.id.btn_getcode);
        img_code = findViewById(R.id.img_code);
    }


    private void testLoadDialog() {


        final LoadingDialog exitLoginDialog = LoadingDialog.newInstance("云备份", "云备份中，请稍等");
        exitLoginDialog.show(getFragmentManager(), "loading");
        exitLoginDialog.setCancelable(false);
    }


    private void initData() {

        btn_generate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String qrContent = "11111111111111111111111111111";
                Bitmap bitmap = new QREncode.Builder(TestActivity.this)
//                        .setColor(getResources().getColor(R.color.colorPrimary))//二维码颜色
                        .setColors(0xFF0094FF, 0xFFFED545, 0xFF5ACF00, 0xFFFF4081)//二维码彩色
                        .setMargin(0)//二维码边框
                        //二维码类型
                        .setParsedResultType(TextUtils.isEmpty(qrContent) ? ParsedResultType.URI
                                : ParsedResultType.TEXT)
                        //二维码内容
                        .setContents(TextUtils.isEmpty(qrContent) ? "https://github.com/mylhyl" :
                                qrContent)
                        .setSize(500)//二维码等比大小
                        .build().encodeAsBitmap();
                img_code.setImageBitmap(bitmap);
            }
        });

        btn_getcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                Intent intent = new Intent(TestActivity.this, ScannerActivity.class);
//                startActivityForResult(intent,1000);
                testLoadDialog();
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


//        oma方式
        if (resultCode == 1001) {

            LogUtils.v(TAG + data.getStringExtra("result"));
//            authToken(random,seqID,"0");
        }

    }

    private void testWeb3j() {

        try {
            //获取节点运行geth客户端的版本号

            final Web3j web3 = Web3jFactory.build(new HttpService(Constant.GENTH));
            Web3ClientVersion web3ClientVersion = web3.web3ClientVersion().sendAsync().get();
            String clientVersion = web3ClientVersion.getWeb3ClientVersion();
            LogUtils.v(TAG + "clientVersion:" + clientVersion);

            EthGetBalance ethGetBalance = web3
                    .ethGetBalance("0x05CEF8B63fFcDAA1AF8c6b41564B5041d4215b58", DefaultBlockParameterName.PENDING)
                    .sendAsync()
                    .get();
            String wei = ethGetBalance.getBalance().toString();
            double bigDecimal = Convert.fromWei(wei, Convert.Unit.ETHER).doubleValue();
            LogUtils.v(TAG + "ethbalance:" + bigDecimal);


            EthGasPrice ethGasPrice = web3.ethGasPrice().sendAsync().get();

            String gasprice = ethGasPrice.getGasPrice().toString();

            LogUtils.v(TAG + "gasprice:" + gasprice);

            new Thread() {
                @Override
                public void run() {

                    List<EthBlock.TransactionResult> txs = null;
                    try {
                        txs = web3.ethGetBlockByNumber(DefaultBlockParameterName.LATEST, true).send().getBlock().getTransactions();
                        BigInteger time = web3.ethGetBlockByNumber(DefaultBlockParameterName.LATEST, false).send().getBlock().getTimestamp();
                        String sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(time.longValue()));

                        LogUtils.v(TAG + "sdf:" + sdf);
                        LogUtils.v(TAG + "txs:" + txs.size());
                        for (int i = 0; i < txs.size(); i++) {

                            EthBlock.TransactionObject transactionobject = (EthBlock.TransactionObject) txs.get(i);

                            LogUtils.v(TAG + "get().getHash():" + transactionobject.get().getHash());
                            LogUtils.v(TAG + "get().getS():" + transactionobject.get().getNonce());
                            LogUtils.v(TAG + "get().getInput():" + transactionobject.get().getInput());
                            LogUtils.v(TAG + "get().getV():" + transactionobject.get().getV());
                            LogUtils.v(TAG + "get().getBlockHash():" + transactionobject.get().getBlockHash());
                            LogUtils.v(TAG + "get().getBlockNumberRaw():" + transactionobject.get().getBlockNumberRaw());
                            LogUtils.v(TAG + "get().getCreates()):" + transactionobject.get().getCreates());
                            LogUtils.v(TAG + "get().getBlockNumber())):" + transactionobject.get().getBlockNumber());
                            LogUtils.v(TAG + "get().getGas():" + transactionobject.get().getGas());
                            LogUtils.v(TAG + "get().getFrom():" + transactionobject.get().getFrom());
                            LogUtils.v(TAG + "get().getTo():" + transactionobject.get().getTo());


                        }


                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }.start();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }


    public void getETHtras() {

        //设置需要的矿工费
        BigInteger GAS_PRICE = BigInteger.valueOf(22_000_000_000L);
        BigInteger GAS_LIMIT = BigInteger.valueOf(4_300_000);

        //调用的是kovan测试环境，这里使用的是infura这个客户端
        Web3j web3j = Web3jFactory.build(new HttpService(Constant.GENTH));

        //转账人账户地址 0x05CEF8B63fFcDAA1AF8c6b41564B5041d4215b58
        String ownAddress = "0x3907d69517b58355207e9a371add9dbc1e198a5b";
        //被转人账户地址
//        String toAddress = "0xBafcC84cDaD822614C228BB27d10Faa7749bA018";
        String toAddress = "0xcb2b98ec804909147aeaf372c47f1edefa9f63be";
        //转账人私钥
//         Credential 里面保存的是公私钥 和 地址（自己添加的注释）
        Credentials credentials = Credentials.create("0x0771ab7f8e1b7ef2099119ec13c03a71ea5363c7626190de1dabc073032d43b4");

        //        Credentials credentials = WalletUtils.loadCredentials(
        //                "123",
        //                "src/main/resources/UTC--2018-03-01T05-53-37.043Z--d1c82c71cc567d63fd53d5b91dcac6156e5b96b3");

        //getNonce（这里的Nonce我也不是很明白，大概是交易的笔数吧）
        EthGetTransactionCount ethGetTransactionCount = null;
        try {
            ethGetTransactionCount = web3j.ethGetTransactionCount(
                    ownAddress, DefaultBlockParameterName.LATEST).sendAsync().get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        BigInteger nonce = ethGetTransactionCount.getTransactionCount();

//        tokenaddr:0xBafcC84cDaD822614C228BB27d10Faa7749bA018ethcount:500000000000000000gasprice:5000000000gasplimit:15868nonce:16
//        BigInteger nonce1 = new BigInteger("16");
//        BigInteger GAS_PRICE = new BigInteger("50000000000");
//        BigInteger GAS_LIMIT = new BigInteger("158680");
//        BigInteger value = new BigInteger("500000000000000000");
//        String  toAddress = "0xBafcC84cDaD822614C228BB27d10Faa7749bA018";

        //创建交易，这里是转0.5个以太币
        BigInteger value = Convert.toWei("0.5", Convert.Unit.ETHER).toBigInteger();
        RawTransaction rawTransaction = RawTransaction.createEtherTransaction(
                nonce, GAS_PRICE, GAS_LIMIT, toAddress, value);
        LogUtils.v(TAG + "nonce:" + nonce + "CAS_PRICE:" + GAS_PRICE + "GAS_LIMIT:" + GAS_LIMIT + "toAddress:" + toAddress + "value:" + value);
        //签名Transaction，这里要对交易做签名
        byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
//        String hexValue = Numeric.toHexString(signedMessage);
//        String hexValue = "0xf86d0485051f4d5c0083419ce094bafcc84cdad822614c228bb27d10faa7749ba0188806f05b59d3b200000077a019e5883aac42fb87b8c693ab7c0f9e1b88a612e9f3daaba5d495bfac7e0b39b1a0a2d2a64bfcde4ab1324e44d07ba25ec6247b3b2704d03d97cbc8fb801e992b65";
        String hexValue = "0xf86c06850ba43b7400821d4b94cb2b98ec804909147aeaf372c47f1edefa9f63be884563918244f40000801ca0f0f484e6c62fb1713f8471736a1f401ab688857ebcbe5ba2f827e22a19fe0a3aa077306144db14a2752de4cee9472756e141a437fb9bbc25b40cca62639fb68eb2";
        LogUtils.v(TAG + "hexValue:" + hexValue);

        //发送交易
        EthSendTransaction ethSendTransaction =
                null;
        try {
            ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        String transactionHash = ethSendTransaction.getTransactionHash();

//        获得到transactionHash后就可以到以太坊的网站上查询这笔交易的状态了
        System.out.println(transactionHash);
////        web3j = Web3jFactory.build(new HttpService());
//        EthTransaction ethTransaction = null;
//        try {
//            ethTransaction = web3j.ethGetTransactionByHash("0x949bb1e5460936bc663e4fcaae5d98a499abd2daa724dada6d07c5f951b44928").sendAsync().get();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        } catch (ExecutionException e) {
//            e.printStackTrace();
//        }
//
//        org.web3j.protocol.core.methods.response.Transaction transactionResult = ethTransaction.getResult();
//
//        System.out.println(transactionResult.getValue());

    }


//    /*** 查询代币余额 */
//    public static BigInteger getTokenBalance(Web3j web3j, String fromAddress, String contractAddress) {
//
//        String methodName = "balanceOf";
//        List inputParameters = new ArrayList<>();
//        List<String> outputParameters = new ArrayList<>();
//        Address address = new Address(fromAddress);
//        inputParameters.add(address);
//
//        TypeReference typeReference = new TypeReference() {
//        };
//        outputParameters.add(typeReference);
//        Function function = new Function(methodName, inputParameters, outputParameters);
//        String data = FunctionEncoder.encode(function);
//        Transaction transaction = Transaction.createEthCallTransaction(fromAddress, contractAddress, data);
//
//        EthCall ethCall;
//        BigInteger balanceValue = BigInteger.ZERO;
//        try {
//            ethCall = web3j.ethCall(transaction, DefaultBlockParameterName.LATEST).send();
//            List results = FunctionReturnDecoder.decode(ethCall.getValue(), function.getOutputParameters());
//            balanceValue = (BigInteger) results.get(0).getValue();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return balanceValue;
//    }


    public void TransactionTest() {

        //设置需要的矿工费
        BigInteger GAS_PRICE = BigInteger.valueOf(25200);
        BigInteger GAS_LIMIT = BigInteger.valueOf(21000);
        LogUtils.v(TAG + "eth:" + Convert.fromWei((25200 * 21000) + "", Convert.Unit.ETHER));

        //调用的是kovan测试环境，这里使用的是infura这个客户端
        Web3j web3j = Web3jFactory.build(new HttpService(Constant.GENTH));
        //转账人账户地址

        String ownAddress = "0xBafcC84cDaD822614C228BB27d10Faa7749bA018";
        //被转人账户地址
        String toAddress = "0x05CEF8B63fFcDAA1AF8c6b41564B5041d4215b58";
        //转账人私钥
        Credentials credentials = Credentials.create("9f6b42cb350cc6fb965d06851aedee58850edd0c8c8c4d796a3ada21d2fc061d");
        //        Credentials credentials = WalletUtils.loadCredentials(
        //                "123",
        //                "src/main/resources/UTC--2018-03-01T05-53-37.043Z--d1c82c71cc567d63fd53d5b91dcac6156e5b96b3");

        //getNonce（这里的Nonce我也不是很明白，大概是交易的笔数吧）
        EthGetTransactionCount ethGetTransactionCount = null;
        try {
            ethGetTransactionCount = web3j.ethGetTransactionCount(
                    ownAddress, DefaultBlockParameterName.LATEST).sendAsync().get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {

            e.printStackTrace();
        }
        BigInteger nonce = ethGetTransactionCount.getTransactionCount();

        LogUtils.v(TAG + "NOCE:" + nonce);
        //创建交易，这里是转0.5个以太币
        BigInteger value = Convert.toWei("0.5", Convert.Unit.ETHER).toBigInteger();
        RawTransaction rawTransaction = RawTransaction.createEtherTransaction(
                nonce, GAS_PRICE, GAS_LIMIT, toAddress, value);

        //签名Transaction，这里要对交易做签名
        byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
        String hexValue = Numeric.toHexString(signedMessage);

        //发送交易
        EthSendTransaction ethSendTransaction =
                null;
        try {
            ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        String transactionHash = ethSendTransaction.getTransactionHash();


        //获得到transactionHash后就可以到以太坊的网站上查询这笔交易的状态了
        System.out.println(transactionHash);
    }

    private TextView receive_tv;
    private Button send_tv;
    private Button start_service_tv;
    private MessageBroadcastReceiver receiver;

    private void registerBroadcast() {

        receiver = new MessageBroadcastReceiver();
        IntentFilter filter = new IntentFilter("com.commonlibrary.mina.broadcast");
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver, filter);
    }

    private void initView1() {

        receive_tv = findViewById(R.id.receive_tv);
        start_service_tv = this.findViewById(R.id.start_service_tv);
        start_service_tv.setOnClickListener(this);
        send_tv = this.findViewById(R.id.send_tv);
        send_tv.setOnClickListener(this);

    }

    MianManager mianManager;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.start_service_tv:
                String request = "0000007503112020000000000000000000000000201808151111180101000102152100129258d969eef6ecad3c28986031070769500116399000479603973";
                mianManager = MianManager.getManager();
                mianManager.request(getApplicationContext(), request, new MinaResultLIstener() {
                    @Override
                    public void messageReceived(IoSession session, Object message) {

                        LogUtils.v(TAG + "message:" + message);
                        LogUtils.v(TAG + "Thread:" + Thread.currentThread().getName());
                    }

                    @Override
                    public void exceptionCaught(IoSession session, Throwable cause) {

                        LogUtils.v(TAG + "message:" + cause.getMessage());

                    }
                });
                break;
            case R.id.send_tv:

                Log.e("tag", "点击发送消息");

                mianManager.shutDown();

                break;

        }
    }

    private void unregisterBroadcast() {

        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterBroadcast();

    }

    private class MessageBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            receive_tv.setText(intent.getStringExtra("message"));
        }
    }

    public void test() {

        byte[] input = "0A06B0A244A68A097023CE95C9883D1293779E8F".getBytes(Charset.forName("UTF-8"));


        byte[] res = Hash.sha3(input);

        String sha3256 = Hex.toHexString(res);
        System.out.println("sha3-256:" + sha3256 + ",lengh=" + sha3256.length());


    }


    private void getDataAsync() {

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://api.etherscan.io/api?module=account&action=txlist&address=0x4dd9d887c79a04c1f4ef186a1590e7da1c5bf6ef&startblock=0&endblock=99999999&sort=asc&apikey=YourApiKeyToken")
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {

                if(response.isSuccessful()){

                    //回调的方法执行在子线程。
                    Log.d("kwwl","获取数据成功了");
                    Log.d("kwwl","response.code()=="+response.code());
                    String result = response.body().string();

                    Log.d("kwwl","response.body().string()=="+result);

                    Gson gson2 = new GsonBuilder().disableHtmlEscaping().create();
                    ReqTransnation reqTransBean =  gson2.fromJson(result,ReqTransnation.class);
                  LogUtils.v(TAG+"reqTransBean:"+reqTransBean);

                }
            }
        });
    }


}

